package com.example.demo.service;

import com.example.demo.GoodsJPARepository;
import com.example.demo.SupplierJPARepository;
import com.example.demo.entity.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class SupplierService {

    @Autowired
    private SupplierJPARepository supplierRepository;

    public Supplier addSupplier(Supplier supplier){return supplierRepository.saveAndFlush(supplier);}

    public Supplier getSupplier(long id){return supplierRepository.getReferenceById(id);}

    public void updateSupplier(long id,Supplier supplier){
        supplierRepository.save(supplier);}

    public void deleteSupplier(long id){
        supplierRepository.deleteById(id);}

    public List<Supplier> findSupplier(int id, String name, String phoneNumber) {
        Specification<Supplier> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (id >= 0) {
                predicateList.add(criteriaBuilder.like(root.get("id"), "%" + id + "%"));
            }
            if ((name != null)) {
                predicateList.add(criteriaBuilder.like(root.get("name"), "%"+name+"%"));
            }
            if(phoneNumber!=null){
                predicateList.add(criteriaBuilder.equal(root.get("phoneNumber"),phoneNumber));
            }
            Predicate[] predicates = predicateList.toArray(new Predicate[predicateList.size()]);
            return criteriaBuilder.and(predicates);
        };

        List<Supplier> result= supplierRepository.findAll(specification);
        return result;
    }
}